package org.imlinker.plugin;

import java.awt.GridLayout;

import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.imlinker.core.Core;
import org.imlinker.util.PasswordMask;

public class AccountManager {

	public static PluginAccount getAccount(String pluginName, String id) {

		String username = Core.getValue(pluginName + ".account." + id
				+ ".username");
		String password = PasswordMask.getPassword(Core.getValue(pluginName
				+ ".account." + id + ".password"));

		if (username == null && password == null) {
			return createAccount(pluginName, id);
		}

		return new PluginAccount(username, password);
	}

	public static PluginAccount createAccount(String pluginName, String id) {
		JPanel panel = new JPanel();
		panel.setLayout(new GridLayout(3, 2));
		panel.add(new JLabel("UserName:"));
		JTextField userField = new JTextField(15);
		panel.add(userField);
		panel.add(new JLabel("Password:"));
		JPasswordField passField = new JPasswordField(15);
		panel.add(passField);
		panel.add(new JLabel(""));
		JCheckBox box = new JCheckBox("Save password?", false);
		panel.add(box);
		int ret = JOptionPane.showConfirmDialog(null, panel, "Input account",
				JOptionPane.OK_CANCEL_OPTION);
		if (ret == JOptionPane.CANCEL_OPTION) {
			return null;
		}

		String username = userField.getText();
		String password = new String(passField.getPassword());
		PluginAccount account = new PluginAccount(username, password);
		if (box.isSelected()) {
			saveAccount(pluginName, id, account);
		}

		return account;
	}

	public static void saveAccount(String pluginName, String id,
			PluginAccount account) {
		String url = pluginName + ".account." + id;

		Core.setValueAt(url + ".username", account.getUsername());
		Core.setValueAt(url + ".password", PasswordMask.setPassword(account
				.getPassword()));
		Core.save();
	}
}
